<?php
/**
 * Note: 由指定模型引入, 通过 ide-helper:models 生成索引文件后, 能正确解析
 * Date: 2021/9/15
 * Time: 1:06
 */

namespace App\Traits;

use App\Models\Mongo\DailyLog\Base;
use Illuminate\Database\Query\Expression;
use Illuminate\Pagination\LengthAwarePaginator;
use Jenssegers\Mongodb\Collection;
use Jenssegers\Mongodb\Eloquent\Builder;

trait MongoModelTrait
{

    /**
     * mongodb扩展不支持casts属性, 这里手动执行
     * @param $key
     * @param $value
     * @return mixed
     */
    public function setAttribute($key, $value)
    {
        if ($this->hasCast($key)) {
            $value = $this->castAttribute($key, $value);
        }
        return parent::setAttribute($key, $value);
    }

    /**
     * aggregate
     * @param array $aggregate
     * @return Base|\App\Models\Mongo\PlayerCache\Base|Expression|Builder
     */
    public static function aggregateStat(array $aggregate)
    {
        return self::raw(function (Collection $collection) use ($aggregate) {
            return $collection->aggregate($aggregate);
        });
    }

    /**
     * aggregate 分页
     * @param array $match
     * @param array $group
     * @param int $page
     * @param int $pageSize
     * @return LengthAwarePaginator
     */
    public function aggregatePaginate(array $aggregate, int $page = 1, int $pageSize = 20, array $options = [])
    {
        $count = self::raw(function (Collection $collection) use ($aggregate, $options) {
            $aggregate[]['$count'] = 'total';
            return $collection->aggregate($aggregate, $options);
        });
        $totalCount = empty($count[0]) ? 0 : $count[0]->total;
        $items = [];
        if ($totalCount) {
            $items = self::raw(function (Collection $collection) use ($aggregate, $page, $pageSize, $options) {
                $aggregate[]['$skip'] = ($page - 1) * $pageSize;
                $aggregate[]['$limit'] = $pageSize;
                return $collection->aggregate($aggregate, $options);
            });
            $items = $items->toArray();
        }
        return new LengthAwarePaginator($items, $totalCount, $pageSize);
    }
}
